import axios from 'axios'
import store from '@/store'
import {
  Message
} from 'element-ui'

const service = axios.create({
  baseURL: "http://localhost:8081/api/",
  timeout: 20000,
})

service.interceptors.request.use(
  function (config) {
    if (store.getters['user/token']) {
      config.headers.Token = store.getters['user/token'];
    };
    return config;
  },
  function (error) {
    return Promise.reject(error);
  }
)

service.interceptors.response.use(
  response => {
    const res = response.data;
    const token = response.headers.token;

    // 保存token
    if (token) {
      store.dispatch('user/token', token);
    }

    // 状态码不等于 000000  则弹出异常信息
    if (res.code !== undefined && res.code !== '000000') {
      Message({
        message: res.message || '未知错误',
        type: 'error',
        duration: 5 * 1000
      })

      return Promise.reject(response);
    }

    return res.data;
  },
  error => {
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })

    return Promise.reject(error);
  }
)

export default service